using System;
using UnityEngine;
using QFramework;
using System.Collections.Generic;
using Random = UnityEngine.Random;

namespace ProjectSurvivor
{
	public partial class EnemyGenerator : ViewController
	{
		[SerializeField]
		public LevelConfig Config;


		public bool LastWave => WavesCount == mTotalCount;
		public EnemyWave CurrentWave => mCurrentWave;
		public static BindableProperty<int> EnemyCount = new BindableProperty<int>(0);

		private Queue<EnemyWave> enemyWavesQueue = new Queue<EnemyWave>();
		
		public int WavesCount = 0;
		private EnemyWave mCurrentWave = null; // 当前波次
		
		private int mTotalCount = 0; // 总波次
		
		private float mCurrentGeneratorSeconds = 0f; // 敌人生成倒计时
		private float mCurrentWaveSeconds = 0f; // 波次结束倒计时
		

		private void Start()
		{
			foreach (var enemyWaveGroup in Config.EnemyWaveGroups)
			{
				foreach (var enemyWave in enemyWaveGroup.Waves)
				{
					mTotalCount++;
					enemyWavesQueue.Enqueue(enemyWave);
				}
			}
		}
		private void Update()
		{
			if (mCurrentWave is null)
			{
				if (enemyWavesQueue.Count > 0)
				{
					mCurrentWave = enemyWavesQueue.Dequeue();
					WavesCount++;
					mCurrentGeneratorSeconds = 0f;
					mCurrentWaveSeconds = 0f;
				}
			}
			else
			{
				mCurrentGeneratorSeconds += Time.deltaTime;
				mCurrentWaveSeconds += Time.deltaTime;
				
				// 持续生成敌人
				if (mCurrentGeneratorSeconds >= mCurrentWave.GenerateDuration)
				{
					mCurrentGeneratorSeconds = 0f;
				
					Player player = Player.Default;

					if (player)
					{
						var XOrY = RandomUtility.Choose(-1, 1);
						var pos = Vector2.zero;

						if (XOrY == -1)
						{
							pos.x = RandomUtility.Choose(CameraController.LBTrans.position.x, CameraController.RTTrans.position.x);
							pos.y = Random.Range(CameraController.LBTrans.position.y, CameraController.RTTrans.position.y);
						}
						else
						{
							pos.x = Random.Range(CameraController.LBTrans.position.x, CameraController.RTTrans.position.x);
							pos.y = RandomUtility.Choose(CameraController.LBTrans.position.y, CameraController.RTTrans.position.y);
						}
						
						mCurrentWave.EnemyPrefab.Instantiate()
							.Position(pos)
							.Self(self =>
							{
								var enemy = self.GetComponent<IEnemy>();
								enemy.SetSpeedScale(mCurrentWave.SpeedScale);
								enemy.SetHPScale(mCurrentWave.HPScale);
							})
							.Show();
					}
				}
				
				// 判断波次是否结束
				if (mCurrentWaveSeconds >= mCurrentWave.Seconds)
				{
					mCurrentWave = null;
				}
			}

		}
	}
}
